<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="onChange"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="upload"
      :class="{disabled:fileList.length>0}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="isshowprogress"
      :percentage="percentage"
      style="width:146px"
      :show-text="false"
    />
    <el-dialog
      title="预览头像"
      :visible="isShowDialog"
      @close="isShowDialog = false"
    >
      <el-row type="flex" justify="center">
        <img :src="previewImg" alt="" width="100%">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID2wc4HFxRggU4ScXGn69yb092wgDXcT7X',
  SecretKey: 'EDzWorjMktnTv75nHWWHo7D4g6IFyTkl'
})
export default {
  data() {
    return {
      fileList: [],
      isShowDialog: false,
      previewImg: '',
      percentage: 0,
      isshowprogress: false
    }
  },
  methods: {
    onPreview(file) {
      this.isShowDialog = true
      this.previewImg = file.url
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('图片大小不能超过2M')
        return false
      }
      const allowedType = ['image/jpeg', 'image/png']
      if (allowedType.indexOf(file.type) === -1) {
        this.$message.warning('只支持jpg和png格式的图片')
        return false
      }
    },
    upload(params) {
      this.isshowprogress = true
      cos.putObject({
        Bucket: '68hr-1300310660', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: Date.now().toString(36) + params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: progressData => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          this.fileList[0].status = 'success'
          this.fileList[0].url = 'http://' + data.Location
        } else {
          this.$message.error(err.message)
        }
        setTimeout(() => {
          this.isshowprogress = false
        }, 1000)
      })
    }

  }
}
</script>

<style lang="scss" scoped>
  ::v-deep   .disabled {
 .el-upload--picture-card {
    display: none;
  }
}
</style>
